package blog.com.mw.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import blog.com.mw.base.ResultData;
import blog.com.mw.dao.ArticleDao;
import blog.com.mw.dao.CategoryDao;
import blog.com.mw.dao.DiscussDao;
import blog.com.mw.dao.LabelDao;
import blog.com.mw.dao.UserDao;
import blog.com.mw.pojo.po.ArticlePO;
import blog.com.mw.pojo.po.CategoryPO;
import blog.com.mw.pojo.po.CategoryTypePO;
import blog.com.mw.pojo.po.DiscussPO;
import blog.com.mw.pojo.po.LabelPO;
import blog.com.mw.pojo.po.LabelTypePO;
import blog.com.mw.pojo.po.UserPO;
import blog.com.mw.pojo.vo.ArticleVO;
import blog.com.mw.pojo.vo.CategoryVO;
import blog.com.mw.pojo.vo.DiscussVO;
import blog.com.mw.pojo.vo.LabelVO;
import blog.com.mw.service.ArticleService;
import blog.com.mw.util.HtmlConvert;

@Transactional
@Service("articleService")
public class ArticleServiceImpl implements ArticleService {

	/**
	 * 注入ArticleDao
	 */
	@Autowired
	private ArticleDao dao;
	/**
	 * 注入ArticleDao
	 */
	@Autowired
	private CategoryDao categoryDao;
	/**
	 * 注入ArticleDao
	 */
	@Autowired
	private LabelDao labelDao;
	/**
	 * 注入ArticleDao
	 */
	@Autowired
	private DiscussDao discussDao;
	/**
	 * 注入ArticleDao
	 */
	@Autowired
	private UserDao userDao;
	/**
	 * 根据用户ID返回用户对应的文章
	 */
	@Override
	public ResultData getArticleByUserId(int userId,int pageNum,int pageSize) {
		ResultData rs = null;
		Map<String,Object> data = null;
		try {
			PageHelper.startPage(pageNum, pageSize);
			List<ArticlePO> articlePos = dao.getArticleByUserId(Long.valueOf(userId));
			List<ArticleVO> articleVos = new ArrayList<>();
			if(articlePos!=null) {
				data = new HashMap<>();
				articlePos.forEach(item->{
					ArticleVO vo = new ArticleVO();
					vo.poToVo(item);
					//查找分类
					CategoryPO categoryPo = categoryDao.getCategoryByArticleId(item.getId());
					CategoryVO categoryVo = new CategoryVO();
					categoryVo.poToVo(categoryPo);
					vo.setCategoryVo(categoryVo);
					//查找标签
					List<LabelPO> labelPos = labelDao.getLabelByArticleId(item.getId());
					List<LabelVO> labelVos = new ArrayList<>();
					labelPos.forEach(label->{
						LabelVO labelVo = new LabelVO();
						labelVo.poToVo(label);
						labelVos.add(labelVo);
					});
					vo.setLabelVos(labelVos);
					//查找评论
					List<DiscussPO> discussPos = discussDao.getDiscussByArticleId(item.getId());
					List<DiscussVO> discussVos = new ArrayList<>();
					discussPos.forEach(discuss->{
						UserPO discusser = userDao.getUserById(discuss.getUserId());
						DiscussVO discussVo = new DiscussVO();
						discussVo.poToVo(discuss);
						discussVo.setAvatar(discusser.getAvatar());
						discussVo.setDiscusser(discusser.getName());
						discussVos.add(discussVo);
					});
					vo.setDiscussVos(discussVos);
					//把数据存进VOS中
					articleVos.add(vo);
				});
				PageInfo<ArticleVO> pageInfo = new PageInfo<ArticleVO>(articleVos);
				pageInfo.setTotal(dao.getArticleByUserId(Long.valueOf(userId)).size());
				data.put("data", pageInfo);
				rs = ResultData.getOk();
				rs.setData(data);
				rs.setMsg(articlePos.size()>0?"获取成功！":"无数据！");
			}else {
				rs = ResultData.getFail();
				rs.setMsg("获取失败！");
				rs.setData(data);
			}
		}catch(Exception e) {
			e.printStackTrace();
			rs = ResultData.getFail();
			rs.setMsg("未知异常");
		}
		return rs;
	}
	/**
	 * 根据ID返回文章
	 */
	@Override
	public ResultData getArticleById(int id) {
		ResultData rs = null;
		Map<String,Object> data = null;
		try {
			ArticlePO article = dao.getArticleById(Long.valueOf(id));
			if(article != null) {
				data = new HashMap<>();
				ArticleVO vo = new ArticleVO();
				vo.poToVo(article);
				//查找分类
				CategoryPO categoryPo = categoryDao.getCategoryByArticleId(article.getId());
				CategoryVO categoryVo = new CategoryVO();
				categoryVo.poToVo(categoryPo);
				vo.setCategoryVo(categoryVo);
				//查找标签
				List<LabelPO> labelPos = labelDao.getLabelByArticleId(article.getId());
				List<LabelVO> labelVos = new ArrayList<>();
				labelPos.forEach(label->{
					LabelVO labelVo = new LabelVO();
					labelVo.poToVo(label);
					labelVos.add(labelVo);
				});
				vo.setLabelVos(labelVos);
				//查找评论
				List<DiscussPO> discussPos = discussDao.getDiscussByArticleId(article.getId());
				List<DiscussVO> discussVos = new ArrayList<>();
				discussPos.forEach(discuss->{
					UserPO discusser = userDao.getUserById(discuss.getUserId());
					DiscussVO discussVo = new DiscussVO();
					discussVo.poToVo(discuss);
					discussVo.setAvatar(discusser.getAvatar());
					discussVo.setDiscusser(discusser.getName());
					discussVos.add(discussVo);
				});
				vo.setDiscussVos(discussVos);
				rs = ResultData.getOk();
				data.put("data", vo);
				rs.setMsg("获取成功");
				rs.setData(data);
			}else {
				rs = ResultData.getFail();
				rs.setMsg("文章不存在！");
			}
		}catch(Exception e) {
			e.printStackTrace();
			rs = ResultData.getFail();
			rs.setMsg("未知异常");
		}
		return rs;
	}
	
	/**
	 * 根标签或者分类获取文章
	 */
	@Override
	public ResultData getArticleByContent(int id , Boolean isLabel,int pageNum,int pageSize) {
		ResultData rs = null;
		Map<String,Object> data = null;
		try {
			PageHelper.startPage(pageNum, pageSize);
			List<Long> ids = isLabel?dao.getIdsByLabel(Long.valueOf(id)):dao.getIdsByCategory(Long.valueOf(id));
			List<ArticlePO> articlePos = new ArrayList<>();
			List<ArticleVO> articleVos = new ArrayList<>();
			if(ids.size()>0) {
				articlePos = isLabel?dao.getArticleByLabelIds(ids)
						:dao.getArticleByCategoryIds(ids);
			}
			if(articlePos!=null) {
				data = new HashMap<>();
				articlePos.forEach(item->{
					ArticleVO vo = new ArticleVO();
					vo.poToVo(item);
					//查找分类
					CategoryPO categoryPo = categoryDao.getCategoryByArticleId(item.getId());
					CategoryVO categoryVo = new CategoryVO();
					categoryVo.poToVo(categoryPo);
					vo.setCategoryVo(categoryVo);
					//查找标签
					List<LabelPO> labelPos = labelDao.getLabelByArticleId(item.getId());
					List<LabelVO> labelVos = new ArrayList<>();
					labelPos.forEach(label->{
						LabelVO labelVo = new LabelVO();
						labelVo.poToVo(label);
						labelVos.add(labelVo);
					});
					vo.setLabelVos(labelVos);
					//查找评论
					List<DiscussPO> discussPos = discussDao.getDiscussByArticleId(item.getId());
					List<DiscussVO> discussVos = new ArrayList<>();
					discussPos.forEach(discuss->{
						UserPO discusser = userDao.getUserById(discuss.getUserId());
						DiscussVO discussVo = new DiscussVO();
						discussVo.poToVo(discuss);
						discussVo.setAvatar(discusser.getAvatar());
						discussVo.setDiscusser(discusser.getName());
						discussVos.add(discussVo);
					});
					vo.setDiscussVos(discussVos);
					//把数据存进VOS中
					articleVos.add(vo);
				});
				PageInfo<ArticleVO> pageInfo = new PageInfo<ArticleVO>(articleVos);
				pageInfo.setTotal(isLabel?dao.getIdsByLabel(Long.valueOf(id)).size():
					dao.getIdsByCategory(Long.valueOf(id)).size());
				data.put("data", pageInfo);
				rs = ResultData.getOk();
				rs.setData(data);
				rs.setMsg(articlePos.size()>0?"获取成功！":"无数据！");
			}else {
				rs = ResultData.getFail();
				rs.setMsg("获取失败！");
				rs.setData(data);
			}
		}catch(Exception e) {
			e.printStackTrace();
			rs = ResultData.getFail();
			rs.setMsg("未知异常");
		}
		return rs;
	}
	
	
	/**
	 *保存文章
	 */
	@Override
	public ResultData saveArticle(ArticleVO article) {
		ResultData rs = null;
		Map<String,Object> data = null;
		try {
			int judge;
			ArticlePO po = new ArticlePO();
			article.voToPo(po);
			if(article.getContent()!=null) {
				po.setContent(HtmlConvert.HtmlConvertContent(article.getContent()));
				List<String> imgs = HtmlConvert.getPirtureByContent(article.getCode());
				if(imgs != null && imgs.size()!=0) {
					po.setPirture(imgs.get(0));
				}else {
					po.setPirture("");
				}
			}
			if(article.getId() == null) {
				po.setAuthor(article.getAuthor());
				po.setUserId(Long.valueOf(article.getUserId()));
				judge = dao.addArticle(po);
			}else {
				judge = dao.updateArticle(po);
			}
			if(judge>0) {
				if(article.getId()==null) {		
					//存储分类
					CategoryTypePO categoryTypePo = categoryDao.getCategoryTypeById
							(Long.valueOf(article.getCategoryVo().getTypeId()));
					CategoryPO categoryPo = new CategoryPO(); 
					categoryPo.setArticleId(po.getId());
					categoryPo.setTypeId(categoryTypePo.getId());
					categoryPo.setContent(categoryTypePo.getContent());
					categoryDao.addCategory(categoryPo);
					//存储标签
					article.getLabelVos().forEach(item->{
						LabelTypePO typePo = labelDao.getLabelTypeByContent(item.getContent());
						//判断标签是否存在
						if(typePo == null) {
							typePo = new LabelTypePO();
							typePo.setContent(item.getContent());
							labelDao.addLabelType(typePo);
						}
						LabelPO labelPo = new LabelPO();
						labelPo.setArticleId(po.getId());
						labelPo.setContent(item.getContent());
						labelPo.setTypeId(typePo.getId());
						labelDao.addLabel(labelPo);
					});
				}
				rs = ResultData.getOk();
				data = new HashMap<>();
				data.put("id", po.getId().toString());
				rs.setData(data);
				rs.setMsg("保存成功！");
			}else {
				rs = ResultData.getFail();
				rs.setMsg("保存失败！");
			}
		}catch(Exception e) {
			e.printStackTrace();
			rs = ResultData.getFail();
			rs.setMsg("未知异常");
		}
		return rs;
	}
	
	/**
	 * 删除文章
	 */
	@Override
	public ResultData delArticle(List<Integer> ids) {
		ResultData rs = null;
		try {
			if(ids.size()==0) {
				rs = ResultData.getFail();
				rs.setMsg("参数不得为空！");
				return rs;
			}
			int delSize = dao.delArticle(ids);
			if(delSize>0) {
				rs = ResultData.getOk();
				rs.setMsg(delSize==ids.size()?"删除成功！":"部分数据未删除成功！");
			}else {
				rs = ResultData.getFail();
				rs.setMsg("删除失败！");
			}
		}catch(Exception e) {
			e.printStackTrace();
			rs = ResultData.getFail();
			rs.setMsg("未知异常");
		}
		return rs;
	}
	@Override
	public ResultData getAllArticle(int pageNum,int pageSize,String keyword) {
		ResultData rs = null;
		Map<String,Object> data = null;
		try {
			PageHelper.startPage(pageNum, pageSize,true);
			List<ArticlePO> articlePos = dao.getAllArticle(keyword);
			List<ArticleVO> articleVos = new ArrayList<>();
			if(articlePos!=null) {
				data = new HashMap<>();
				articlePos.forEach(item->{
					ArticleVO vo = new ArticleVO();
					vo.poToVo(item);
					//查找分类
					CategoryPO categoryPo = categoryDao.getCategoryByArticleId(item.getId());
					CategoryVO categoryVo = new CategoryVO();
					categoryVo.poToVo(categoryPo);
					vo.setCategoryVo(categoryVo);
					//查找标签
					List<LabelPO> labelPos = labelDao.getLabelByArticleId(item.getId());
					List<LabelVO> labelVos = new ArrayList<>();
					labelPos.forEach(label->{
						LabelVO labelVo = new LabelVO();
						labelVo.poToVo(label);
						labelVos.add(labelVo);
					});
					vo.setLabelVos(labelVos);
					//查找评论
					List<DiscussPO> discussPos = discussDao.getDiscussByArticleId(item.getId());
					List<DiscussVO> discussVos = new ArrayList<>();
					discussPos.forEach(discuss->{
						UserPO discusser = userDao.getUserById(discuss.getUserId());
						DiscussVO discussVo = new DiscussVO();
						discussVo.poToVo(discuss);
						discussVo.setAvatar(discusser.getAvatar());
						discussVo.setDiscusser(discusser.getName());
						discussVos.add(discussVo);
					});
					vo.setDiscussVos(discussVos);
					//把数据存进VOS中
					articleVos.add(vo);
				});
				PageInfo<ArticleVO> pageInfo = new PageInfo<ArticleVO>(articleVos);
				pageInfo.setTotal(dao.getAllArticle(keyword).size());
				data.put("data", pageInfo);
				rs = ResultData.getOk();
				rs.setData(data);
				rs.setMsg(articlePos.size()>0?"获取成功！":"无数据！");
			}else {
				rs = ResultData.getFail();
				rs.setMsg("获取失败！");
				rs.setData(data);
			}
		}catch(Exception e) {
			e.printStackTrace();
			rs = ResultData.getFail();
			rs.setMsg("未知异常");
		}
		return rs;
	}

}
